package com.oto.web.resource;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Set;

import javax.jdo.PersistenceManager;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.oto.model.AccountDO;
import com.oto.service.PMF;
import com.sun.jersey.api.view.Viewable;

/**
 * 设置用户的昵称、电话的分享、隐私及同步选项
 * 
 * @author xueqiang.mi
 * @since 2011-1-19
 */
@Path("/settings")
@Component
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class SettingResource extends BaseResource {

	@GET
	public Response getSettings() {
		AccountDO account = accountService.get(getUserName());
		return Response.ok(new Viewable("index", account)).build();
	}

	@POST
	@Consumes("application/x-www-form-urlencoded")
	public Response saveSettings(@FormParam(value = "nickName") String nickName,
			@FormParam(value = "settings-share") int settingShare, @FormParam(value = "settings-privacy") int settingPrivacy,
			@FormParam(value = "settings-sync") Set<Integer> settingSync) throws URISyntaxException {
		PersistenceManager pm = PMF.get();
		try {
			AccountDO account = pm.getObjectById(AccountDO.class, getUserName());
			account.setNickName(nickName);
			account.setSettingShare(settingShare);
			account.setSettingPrivacy(settingPrivacy);
			account.setSettingSync(settingSync);
		} finally {
			pm.close();
		}
		return Response.seeOther(new URI("/home")).build();
	}
}
